package JAVA300.第十一章多线程;

/**
 * 练习threadLocal
 */

public class thread_19_others_6ThreadLocal {

    //默认存储object 添加泛型
   // private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>();
    //更改初始值1-匿名
    /*private static ThreadLocal<Integer> threadLocal = new ThreadLocal<>(){
        @Override
        protected Object initialValue() {
            return 200;
        }
    };*/
    ///更改初始值2-lamda
    private static ThreadLocal<Integer> threadLocal = ThreadLocal.withInitial(()->{
        return 1;
    });

    public static void main(String[] args) {
        System.out.println(Thread.currentThread().getName()+"-->"+threadLocal.get());//main-->null默认初始值为null\

        threadLocal.set(99);


        for (int i=0;i<5;i++){
            new Thread(new MyRun()).start();//开启五个线程 但五个线程的left不影响
        }

    }

    public static class MyRun implements Runnable{
        @Override
        public void run() {

            //threadLocal.set((int)Math.random()*100);
            Integer left =threadLocal.get();
            System.out.println(Thread.currentThread().getName()+"得到了-->"+left);
            threadLocal.set(left-1);
            System.out.println(Thread.currentThread().getName()+"还剩下-->"+threadLocal.get());

        }
    }
}
